
import 'dart:async';

import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';

enum PermissionRequest {
  photos,
  photosAddOnly
}

enum PermissionState {
  notDetermined,     // User has not yet made a choice with regards to this application
  restricted,        // This application is not authorized to access photo data. The user cannot change this application’s status, possibly due to active restrictions. such as parental controls being in place.
  denied,            // User has explicitly denied this application access to photos data.
  authorized,        // User has authorized this application to access photos data.
  limited
}

class GoodpromiseIap {
  static const MethodChannel _methodChannel = MethodChannel('goodpromise.exechina.com/IAP_vip_annual');
  static const EventChannel _eventChannel = EventChannel('goodpromise.exechina.com/IAP_vip_annual_result');

  static Future<void> submitIAPRequest(String productId) async {

    assert(defaultTargetPlatform == TargetPlatform.iOS, "only support ios IAP");
    await _methodChannel.invokeMethod('submitIAPRequest', productId);
  }

  static Future<PermissionState> checkPermission(PermissionRequest status) async {
    if (defaultTargetPlatform == TargetPlatform.iOS) {
      int result = await _methodChannel.invokeMethod('checkPermission', describeEnum(status));
      PermissionState state;
      if (0 == result) { state = PermissionState.notDetermined; }
      else if (1 == result) { state = PermissionState.restricted; }
      else if (2 == result) { state = PermissionState.denied; }
      else if (3 == result) { state = PermissionState.authorized; }
      else { state = PermissionState.limited; }
      return state;
    }
    return Future.value(PermissionState.denied);
  }

  static void onListenPayment(Function(Map) callback) async {

    assert(defaultTargetPlatform == TargetPlatform.iOS, "only support ios IAP");

    _eventChannel.receiveBroadcastStream().listen((event) {
      print("event: $event");
      callback(event);
    }, onDone: (){
      print("GoodpromiseIap onDone");
    }, onError: (e){
      print("GoodpromiseIap exception: $e");
    });
  }
}
